package com.ext.aic.utils;

import com.ext.aic.AICManager;
import com.ext.aic.beans.WhiteListItem;
import com.ext.aic.beans.WhiteListItem_;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import io.objectbox.query.QueryBuilder;

public class WhiteListUtils {

    private static volatile WhiteListUtils instance;

    public static WhiteListUtils getInstance() {
        if (instance == null) {
            synchronized (WhiteListUtils.class) {
                if (instance == null) {
                    instance = new WhiteListUtils();
                }
            }
        }
        return instance;
    }

    private Set<String> whiteList;

    public List<WhiteListItem> getWhiteList() {
        List<WhiteListItem> items = AICManager.getInstance().findAll(WhiteListItem.class);
        whiteList = items.stream().map(WhiteListItem::getUser).collect(Collectors.toSet());
        return items;
    }

    public WhiteListItem findWhiteList(String user) {
        return AICManager.getInstance().findOne(WhiteListItem.class, query -> {
            query.equal(WhiteListItem_.user, user, QueryBuilder.StringOrder.CASE_INSENSITIVE);
        });
    }

    public Set<String> getWhiteListUsers() {
        if (ObjectJudge.isNullOrEmpty(whiteList)) {
            List<WhiteListItem> items = AICManager.getInstance().findAll(WhiteListItem.class);
            whiteList = items.stream().map(WhiteListItem::getUser).collect(Collectors.toSet());
            if (whiteList == null) {
                whiteList = new HashSet<>();
            }
        }
        return whiteList;
    }
}
